package bean;

import java.sql.Connection;
import java.util.HashMap;

import javax.faces.context.FacesContext;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletResponse;

import net.sf.jasperreports.engine.JasperExportManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import util.ConexaoBD;

public class RelatorioBean {
	public static void relatorio(String parametro, String jasper) {
		relatorio(parametro, jasper, "", "");
	}

	public static void relatorio(String parametro, String jasper,
			String dataInicial, String dataFinal) {

		try {
			HashMap<String, String> parameters = new HashMap<String, String>();
			parameters.put("nome", "" + parametro + "%");
			parameters.put("dataInicial", dataInicial);
			parameters.put("dataFinal", dataFinal);

			FacesContext facesContext = FacesContext.getCurrentInstance();
			facesContext.responseComplete();

			ServletContext scontext = (ServletContext) facesContext
					.getExternalContext().getContext();

			Connection con = ConexaoBD.getConnection();

			JasperPrint jasperPrint = JasperFillManager.fillReport(
					scontext.getRealPath("/relatorios/" + jasper + ".jasper"),
					parameters, con);

			ConexaoBD.closeConnection(con);

			HttpServletResponse response = (HttpServletResponse) facesContext
					.getExternalContext().getResponse();
			response.setContentType("application/pdf");
			byte x1[] = JasperExportManager.exportReportToPdf(jasperPrint);
			response.getOutputStream().write(x1);

		} catch (Exception e) {

			e.printStackTrace();

		}

	}

}
